#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../ModuleB/class.h"
#include "student.h"

// 加载学生信息 
void loadStudentsFromFile(struct Student students[], int *num_students, struct Course courses[], int num_courses) {
    FILE *file = fopen("student.txt", "r");
    if (file == NULL) {
        printf("无法打开学生文件。\n");
        return;
    }

    char line[100];
    while (fgets(line, sizeof(line), file) != NULL) {
        int course_id;
        int i = 0;
        students[*num_students].total_credits = 0;
        if (sscanf(line, "%d,%[^,]", &students[*num_students].id, students[*num_students].name) == 2) {
            char *token = strtok(line, ",");
            while (token != NULL) {
                token = strtok(NULL, ",");
                if (token != NULL && sscanf(token, "%d", &course_id) == 1) {
                    students[*num_students].selected_courses[i] = course_id;
                    for (int j = 0; j < num_courses; j++) {
                        if (courses[j].code == course_id) {
                            students[*num_students].total_credits += courses[j].credits;
                        }
                    }
                    i++;
                }
            }
            (*num_students)++;
        }
    }
    fclose(file);
}

//保存学生信息
void saveStudentsToFile(struct Student students[], int num_students) {
    FILE *file = fopen("student.txt", "w");
    if (file == NULL) {
        printf("无法保存学生文件。\n");
        return;
    }

    for (int i = 0; i < num_students; i++) {
        fprintf(file, "%d,%s", students[i].id, students[i].name);
        for (int j = 0; students[i].selected_courses[j] != 0; j++) {
            fprintf(file, ",%d", students[i].selected_courses[j]);
        }
        fprintf(file, "\n");
    }
    fclose(file);
}

//添加学生信息
void addStudent(struct Student students[], int *num_students, struct Course courses[], int *num_courses) {
    if (*num_students >= 100) {
        printf("学生数量已达上限，无法添加更多学生。\n");
        return;
    }

    printf("请输入学生学号: ");
    scanf("%d", &students[*num_students].id);
    printf("请输入学生姓名: ");
    scanf(" %[^\n]s", students[*num_students].name);
    students[*num_students].total_credits = 0;
    int selected_course_count;
    printf("请输入学生选课数量: ");
    scanf("%d", &selected_course_count);
    if (selected_course_count > 10) {
        printf("选课数量超过上限，将仅添加前10门课程。\n");
        selected_course_count = 10;
    }
    printf("请输入学生选课编号 (最多10门):\n");
    for (int i = 0; i < selected_course_count; i++) {
        int course_id;
        scanf("%d", &course_id);
        // 检查课程是否存在并且学生的选课数量未超过上限
        int course_found = 0;
        for (int j = 0; j < *num_courses; j++) {
            if (courses[j].code == course_id) {
                if (students[*num_students].total_credits + courses[j].credits <= 30 &&
                    courses[j].enrolled_students < courses[j].max_students) {
                    students[*num_students].selected_courses[i] = course_id;
                    students[*num_students].total_credits += courses[j].credits;
                    courses[j].enrolled_students++; // 增加课程的已选人数
                    course_found = 1;
                    break;
                } else {
                    if (students[*num_students].total_credits + courses[j].credits > 30) {
                        printf("学生选课总学分已达上限，无法再选课程编号 %d。\n", course_id);
                    }
                    if (courses[j].enrolled_students >= courses[j].max_students) {
                        printf("课程编号 %d 已达到人数上限，无法再选。\n", course_id);
                    }
                    break;
                }
            }
        }
        if (!course_found) {
            printf("课程编号 %d 不存在，将不被添加到选课列表中。\n", course_id);
        }
    }

    // 打开 student.txt 文件以附加（追加）模式写入学生信息
    FILE *studentFile = fopen("student.txt", "a");
    if (studentFile == NULL) {
        printf("无法打开学生文件。\n");
        return;
    }

    // 写入学生信息到文件
    fprintf(studentFile, "%d,%s,", students[*num_students].id, students[*num_students].name);
    for (int i = 0; i < selected_course_count-1; i++) {
        fprintf(studentFile, "%d,", students[*num_students].selected_courses[i]);
    }
    fprintf(studentFile, "%d\n", students[*num_students].selected_courses[selected_course_count-1]);
    fclose(studentFile);
    (*num_students)++;
    logOperation("新增学生信息");

    // 更新 class.txt 文件中的课程信息
    saveCoursesToFile(courses, *num_courses);
}

//显示学生信息
void viewStudentDetails(struct Student students[], int num_students, int student_id) {
    for (int i = 0; i < num_students; i++) {
        if (students[i].id == student_id) {
            printf("学生学号: %d\n", students[i].id);
            printf("学生姓名: %s\n", students[i].name);
            printf("已选课程列表:\n");
            for (int j = 0; students[i].selected_courses[j] != 0; j++) {
                printf("%d\n", students[i].selected_courses[j]);
            }
            printf("已选课程总计学分: %d\n", students[i].total_credits);
            return;
        }
    }
    printf("未找到学号为 %d 的学生。\n", student_id);
}

//修改学生信息
void modifyStudent(struct Student students[], int num_students, int student_id, struct Course courses[], int num_courses) {
    for (int i = 0; i < num_students; i++) {
        if (students[i].id == student_id) {
            printf("请输入新的学生姓名: ");
            scanf(" %[^\n]s", students[i].name);
            int selected_course_count;
            printf("请输入学生选课数量: ");
            scanf("%d", &selected_course_count);
            if (selected_course_count > 10) {
                printf("选课数量超过上限，将仅修改前10门课程。\n");
                selected_course_count = 10;
            }
            printf("请输入学生选课编号 (最多10门):\n");
            for (int j = 0; j < selected_course_count; j++) {
                int course_id;
                scanf("%d", &course_id);

                // 查找学生原来选的课程
                for (int k = 0; k < 10; k++) {
                    int old_course_id = students[i].selected_courses[k];
                    if (old_course_id != 0) {

                        // 找到原来选的课程，更新已选人数
                        for (int m = 0; m < num_courses; m++) {
                            if (courses[m].code == old_course_id) {
                                courses[m].enrolled_students--;
                                break;
                            }
                        }
                    } else {
                        break; // 学生选课列表中没有更多课程
                    }
                }

                // 检查课程是否存在并且学生的选课数量未超过上限
                int course_found = 0;
                for (int k = 0; k < num_courses; k++) {
                    if (courses[k].code == course_id) {
                        if (students[i].total_credits + courses[k].credits <= 30 &&
                            courses[k].enrolled_students < courses[k].max_students) {

                            students[i].selected_courses[j] = course_id;
                            students[i].total_credits += courses[k].credits;
                            courses[k].enrolled_students++; // 增加课程的已选人数

                            course_found = 1;
                            break;
                        } else {
                            if (students[i].total_credits + courses[k].credits > 30) {
                                printf("学生选课总学分已达上限，无法再选课程编号 %d。\n", course_id);
                            }
                            if (courses[k].enrolled_students >= courses[k].max_students) {
                                printf("课程编号 %d 已达到人数上限，无法再选。\n", course_id);
                            }
                            break;
                        }
                    }
                }
                if (!course_found) {
                    printf("课程编号 %d 不存在，将不被添加到选课列表中。\n", course_id);
                }
            }

            // 更新 student.txt 文件中的学生信息
            saveStudentsToFile(students, num_students);

            // 更新 class.txt 文件中的课程信息
            saveCoursesToFile(courses, num_courses);
            logOperation("修改学生信息");
            return;
        }
    }
    printf("未找到学号为 %d 的学生。\n", student_id);
}

//删除学生信息
void deleteStudent(struct Student students[], int *num_students, int student_id, struct Course courses[], int *num_courses) {
    for (int i = 0; i < *num_students; i++) {
        if (students[i].id == student_id) {

            // 查找学生原来选的课程
            for (int j = 0; j < 10; j++) {
                int course_id = students[i].selected_courses[j];
                if (course_id != 0) {

                    // 找到原来选的课程，更新已选人数
                    for (int k = 0; k < *num_courses; k++) {
                        if (courses[k].code == course_id) {
                            courses[k].enrolled_students--;
                            break;
                        }
                    }
                } else {
                    break; // 学生选课列表中没有更多课程
                }
            }

            // 移除学生并将后续学生向前移动
            for (int j = i; j < (*num_students - 1); j++) {
                students[j] = students[j + 1];
            }
            (*num_students)--;

            // 更新 student.txt 文件中的学生信息
            saveStudentsToFile(students, *num_students);

            // 更新 class.txt 文件中的课程信息
            saveCoursesToFile(courses, *num_courses);
            logOperation("删除学生信息");
            return;
        }
    }
    printf("未找到学号为 %d 的学生。\n", student_id);
}
